package b.acct.test

import java.net.URLEncoder
import java.nio.charset.Charset

import akka.actor.Actor.Receive
import akka.actor.{Actor, ActorSystem, Props}
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import akka.util.ByteString
import b.gate.to.juhe.C天气服务方
import org.squbs.env.EnvironmentResolverRegistry
import org.squbs.httpclient.{ClientFlow, HttpEndpoint}
import org.squbs.resolver.ResolverRegistry

import scala.concurrent.{Await, Future}
import scala.util.Try
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.Promise

/**
  * Created by lenovo on 2016/12/31.
  */
object TryClient extends App {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  // Register EndpointResolver
  EnvironmentResolverRegistry(system).register(DummyDevEnvironmentResolver)
  ResolverRegistry.get(system).register[HttpEndpoint](new SampleEndpointResolver)
  // construct a pool client flow with context type `Int`
  val poolClientFlow = ClientFlow[Int]("sample") // Only this line is specific to squbs
  def call(uriX: String): Unit = {
    println(s"Call to [$uriX]")
    val responseFuture: Future[(Try[HttpResponse], Int)] =
      Source.single(HttpRequest(uri = uriX) -> 42)
        .via(poolClientFlow)
        .runWith(Sink.head)
    responseFuture.map { f =>
      f._1.map { rs =>
        rs.entity.dataBytes.map { data =>
          println(data.decodeString(Charset.defaultCharset()))
        }. runWith(Sink.head)
      }
    }
//    val f = Await.result(responseFuture, 10 seconds)
//    println(f)
  }
  val city = URLEncoder.encode("北京", "UTF-8")
  val uriA = s"/weather/index?cityname=$city&key=542bbe7c227fdd2ba8e812f99b4c239e"
  call(uriA)
//  val juhe = system.actorOf(Props[ToJuhe], "Juhe")
//  juhe ! uriA
}

//class ToJuhe extends Actor with C天气服务方 {
//  override def receive: Receive = {
//    case uri: String =>
//      call(uri).map { f =>
//        f.runFold(ByteString(""))(_ ++ _).map { data =>
//          val rs = data.decodeString(Charset.defaultCharset())
//          println(s"--RS@Actor\n$rs")
//        }
//      }
//  }
//}
